package x.ovo.wechat.bot.command;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.common.Context;
import x.ovo.wechat.bot.common.command.Command;
import x.ovo.wechat.bot.common.command.CommandExecutor;
import x.ovo.wechat.bot.common.command.CommandManager;
import x.ovo.wechat.bot.common.entity.message.TextMessage;

import java.util.HashMap;
import java.util.Map;

@Slf4j(topic = "指令管理器")
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class DefaultCommandManager implements CommandManager {

    @Getter
    private final Context context;
    private final Map<String, CommandExecutor> map = new HashMap<>(16);

    public static CommandManager create(Context context) {
        DefaultCommandManager manager = new DefaultCommandManager(context);
        context.setCommandManager(manager);
        log.info("指令管理器初始化完成");
        return manager;
    }

    @Override
    public void register(String command, CommandExecutor executor) {
        this.map.put(command, executor);
    }

    @Override
    public void unregister(String command) {
        this.map.remove(command);
    }

    @Override
    public void execute(TextMessage message) {
        try {
            Command command = new Command(message.getContent(), message.isGroup() ? message.getMember().getNickName() : message.getFromUser().getNickName());
            CommandExecutor executor = this.map.get(command.getMainCommand());
            if (executor != null) {
                executor.execute(command, message);
            }
        }catch (Exception e) {
            log.error("指令执行失败", e);
        }
    }
}
